package com.v1.video.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import junit.framework.Assert;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.MotionEvent;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.v1.video.R;
import com.v1.video.widgets.MyDialog;
//import org.qii.weiciyuan.bean.GeoBean;
//import org.qii.weiciyuan.support.lib.MyAsyncTask;
//import org.qii.weiciyuan.support.settinghelper.SettingUtility;

public class Utility {
	public final static String TAG = "Utility";

	private Utility() {
		// Forbidden being instantiated.
	}

	public static String encodeUrl(Map<String, String> param) {
		if (param == null) {
			return "";
		}

		StringBuilder sb = new StringBuilder();

		Set<String> keys = param.keySet();
		boolean first = true;

		for (String key : keys) {
			String value = param.get(key);
			if (!TextUtils.isEmpty(value)) {
				if (first)
					first = false;
				else
					sb.append("&");
				try {
					sb.append(URLEncoder.encode(key, "UTF-8")).append("=")
							.append(URLEncoder.encode(param.get(key), "UTF-8"));
				} catch (UnsupportedEncodingException e) {

				}
			}

		}

		return sb.toString();
	}

	public static Bundle decodeUrl(String s) {
		Bundle params = new Bundle();
		if (s != null) {
			String array[] = s.split("&");
			for (String parameter : array) {
				String v[] = parameter.split("=");
				try {
					params.putString(URLDecoder.decode(v[0], "UTF-8"),
							URLDecoder.decode(v[1], "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();

				}
			}
		}
		return params;
	}

	public static void closeSilently(Closeable closeable) {
		if (closeable != null)
			try {
				closeable.close();
			} catch (IOException ignored) {

			}
	}

	/**
	 * Parse a URL query and fragment parameters into a key-value bundle.
	 */
	public static Bundle parseUrl(String url) {
		// hack to prevent MalformedURLException
		url = url.replace("weiboconnect", "http");
		try {
			URL u = new URL(url);
			Bundle b = decodeUrl(u.getQuery());
			b.putAll(decodeUrl(u.getRef()));
			return b;
		} catch (MalformedURLException e) {
			return new Bundle();
		}
	}

	/*
	 * public static void cancelTasks(MyAsyncTask... tasks) { for (MyAsyncTask
	 * task : tasks) { if (task != null) task.cancel(true); } }
	 */

	/*
	 * public static boolean isTaskStopped(MyAsyncTask task) { return task ==
	 * null || task.getStatus() == MyAsyncTask.Status.FINISHED; }
	 */

	public static void stopListViewScrollingAndScrollToTop(ListView listView) {
		if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
			listView.setSelection(0);
			listView.dispatchTouchEvent(MotionEvent.obtain(
					SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
					MotionEvent.ACTION_CANCEL, 0, 0, 0));

		} else {
			listView.dispatchTouchEvent(MotionEvent.obtain(
					SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
					MotionEvent.ACTION_DOWN, 0, 0, 0));
			listView.dispatchTouchEvent(MotionEvent.obtain(
					SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
					MotionEvent.ACTION_UP, 0, 0, 0));
			listView.setSelection(0);
		}
	}

	/*
	 * public static int dip2px(int dipValue) { float reSize =
	 * GlobalContext.getInstance().getResources().getDisplayMetrics().density;
	 * return (int) ((dipValue * reSize) + 0.5); }
	 * 
	 * public static int px2dip(int pxValue) { float reSize =
	 * GlobalContext.getInstance().getResources().getDisplayMetrics().density;
	 * return (int) ((pxValue / reSize) + 0.5); }
	 */

	/*
	 * public static float sp2px(int spValue) { return
	 * TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue,
	 * GlobalContext.getInstance().getResources().getDisplayMetrics()); }
	 */

	public static int length(String paramString) {
		int i = 0;
		for (int j = 0; j < paramString.length(); j++) {
			if (paramString.substring(j, j + 1).matches("[Α-￥]"))
				i += 2;
			else
				i++;
		}

		if (i % 2 > 0) {
			i = 1 + i / 2;
		} else {
			i = i / 2;
		}

		return i;
	}

	public static boolean isConnected(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();

		return networkInfo != null && networkInfo.isConnected();
	}

	public static boolean isWifi(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
				return true;
			}
		}
		return false;
	}

	public static int getNetType(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			return networkInfo.getType();
		}
		return -1;
	}

	public static boolean isGprs(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			if (networkInfo.getType() != ConnectivityManager.TYPE_WIFI) {
				return true;
			}
		}
		return false;
	}

	public static boolean isSystemRinger(Context context) {
		AudioManager manager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		return manager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
	}

	/*
	 * public static void configVibrateLedRingTone(Notification.Builder builder)
	 * { configRingTone(builder); configLed(builder); configVibrate(builder); }
	 */

	/*
	 * private static void configVibrate(Notification.Builder builder) { if
	 * (SettingUtility.allowVibrate()) { long[] pattern = {0, 200, 500};
	 * builder.setVibrate(pattern); } }
	 */

	/*
	 * private static void configRingTone(Notification.Builder builder) { Uri
	 * uri = null;
	 * 
	 * if (!TextUtils.isEmpty(SettingUtility.getRingtone())) { uri =
	 * Uri.parse(SettingUtility.getRingtone()); }
	 * 
	 * if (uri != null && isSystemRinger(GlobalContext.getInstance())) {
	 * builder.setSound(uri); } }
	 */

	/*
	 * private static void configLed(Notification.Builder builder) { if
	 * (SettingUtility.allowLed()) { builder.setLights(Color.WHITE, 300, 1000);
	 * }
	 * 
	 * }
	 */

	public static String getPicPathFromUri(Uri uri, Activity activity) {
		String value = uri.getPath();

		if (value.startsWith("/external")) {
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = activity.managedQuery(uri, proj, null, null, null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} else {
			return value;
		}
	}

	public static boolean isAllNotNull(Object... obs) {
		for (int i = 0; i < obs.length; i++) {
			if (obs[i] == null) {
				return false;
			}
		}
		return true;
	}

	/*
	 * public static boolean isGPSLocationCorrect(GeoBean geoBean) { double
	 * latitude = geoBean.getLat(); double longitude = geoBean.getLon(); if
	 * (latitude < -90.0 || latitude > 90.0) { return false; } if (longitude <
	 * -180.0 || longitude > 180.0) { return false; } return true; }
	 */

	public static boolean isIntentSafe(Activity activity, Uri uri) {
		Intent mapCall = new Intent(Intent.ACTION_VIEW, uri);
		PackageManager packageManager = activity.getPackageManager();
		List<ResolveInfo> activities = packageManager.queryIntentActivities(
				mapCall, 0);
		return activities.size() > 0;
	}

	public static boolean isIntentSafe(Activity activity, Intent intent) {
		PackageManager packageManager = activity.getPackageManager();
		List<ResolveInfo> activities = packageManager.queryIntentActivities(
				intent, 0);
		return activities.size() > 0;
	}

	public static boolean isGooglePlaySafe(Activity activity) {
		Uri uri = Uri
				.parse("http://play.google.com/store/apps/details?id=com.google.android.gms");
		Intent mapCall = new Intent(Intent.ACTION_VIEW, uri);
		mapCall.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
		mapCall.setPackage("com.android.vending");
		PackageManager packageManager = activity.getPackageManager();
		List<ResolveInfo> activities = packageManager.queryIntentActivities(
				mapCall, 0);
		return activities.size() > 0;
	}

	public static String buildTabText(int number) {

		if (number == 0) {
			return null;
		}

		String num;
		if (number < 99) {
			num = "(" + number + ")";
		} else {
			num = "(99+)";
		}
		return num;

	}

	static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {

		public boolean verify(String s, SSLSession sslsession) {
			return true;
		}
	};

	public static String URLEncoder(String paramString) {
		if ((paramString == null) || ("".equals(paramString)))
			paramString = "";
		else {
			try {
				String str = URLEncoder.encode(paramString, "UTF-8");
				paramString = str;
			} catch (NullPointerException localNullPointerException) {
			} catch (UnsupportedEncodingException localUnsupportedEncodingException) {
			}
		}
		return paramString;
	}

	public static String week(int y, int m, int d) {
		if (m == 1) {
			m = 13;
			y--;
		}
		if (m == 2) {
			m = 14;
			y--;
		}
		int week = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7;
		String weekstr = "";
		switch (week) {
		case 0:
			weekstr = "一";
			break;
		case 1:
			weekstr = "二";
			break;
		case 2:
			weekstr = "三";
			break;
		case 3:
			weekstr = "四";
			break;
		case 4:
			weekstr = "五";
			break;
		case 5:
			weekstr = "六";
			break;
		case 6:
			weekstr = "日";
			break;
		}
		return weekstr;
	}

	/**
	 * 根据时常(秒数)返回时分秒
	 * 
	 * @param time
	 * @return
	 */
	
	public static String getDuration(String duration) {
		String result = "";
		if(duration == null || duration.equals("")){
			return "00:00";
		}
		int time = (int)Float.parseFloat(duration);
		if(time == 3600){
			return "01:00:00";
		}else if(time < 3600){
			if (time / 60 > 0) {
				if(time / 60 < 10){
					result = "0" + time / 60 + ":" + (time % 60 < 10 ? "0"+time % 60 :time % 60);
				}else{
					result = time / 60 + ":" + (time % 60 < 10 ? "0"+time % 60 :time % 60);
				}
			} else {
				result = "00:"+(time<10?"0"+time:time);
			}
		}else if(time > 3600){
			int hour = time / 3600;
			time = time % 3600;
			if (time / 60 > 0) {
				if(time / 60 < 10){
					result = (hour<10?"0"+hour:hour) + ":" + "0" + time / 60 + ":" + (time % 60 < 10 ? "0"+time % 60 :time % 60);
				}else{
					result =  (hour<10?"0"+hour:hour) + ":" + time / 60 + ":" + (time % 60 < 10 ? "0"+time % 60 :time % 60);
				}
			} else {
				result =  (hour<10?"0"+hour:hour) + ":" + "00:"+(time<10?"0"+time:time);
			}
		}
		return result;
	}

	/**
	 * 根据服务器返回数据，取得数据的日期和星期，保存在String数组返回
	 * 
	 * @param dateStr
	 * @return
	 */
	public static String getDate(String dateStr) {
		if (dateStr == null || dateStr.length() == 0 || dateStr.equals("")
				|| dateStr.equals("null"))
			return "";
		String dateResult[] = new String[2];
		String dateArray[], timeArray[];
		// 计算日期数据
		// "2014-05-30 16:20:00.0"
		dateResult = dateStr.split(" ");
		if (dateResult.length < 2) {
			dateResult = dateStr.split("T");
		}
		dateArray = dateResult[0].split("-");
		timeArray = dateResult[1].split(":");
		int year, month, day, hour, min, sec;

		year = Integer.parseInt(dateArray[0]);
		month = Integer.parseInt(dateArray[1]) - 1;
		day = Integer.parseInt(dateArray[2]);

		hour = Integer.parseInt(timeArray[0]);
		min = Integer.parseInt(timeArray[1]);
		if (timeArray[2].contains(".")) {
			int index = timeArray[2].indexOf(".");
			Logger.i(TAG, "分割前秒数据==" + timeArray[2]);
			timeArray[2] = timeArray[2].substring(0, index);
			Logger.i(TAG, "分割后秒数据==" + timeArray[2]);
		}
		sec = Integer.parseInt(timeArray[2]);
		GregorianCalendar gregorianCalendar = new GregorianCalendar(year,
				month, day, hour, min, sec);
		return getHowLongStr(gregorianCalendar, dateStr);
	}

	public static String getHowLongStr(Calendar date, String dateStr) {
		String rs = "";
		Long i = date.getTimeInMillis();
		Date now = new Date();
		Long j = now.getTime();
		long dayTime = 1000 * 60 * 60 * 24;
		long hourTime = 1000 * 60 * 60;
		long minTime = 1000 * 60;
		long secTime = 1000;
		int now11 = (int) (j / dayTime);
		Logger.i(TAG, "now11==" + now11);
		if (((j - i) / dayTime) > 2) {
			// int month = date.get(Calendar.MONTH);
			// int day = date.get(Calendar.DAY_OF_MONTH);
			// int hour = date.get(Calendar.HOUR_OF_DAY);
			// int min = date.get(Calendar.MINUTE);
			// rs = (month + 1) + "月" + (day) + "日" + " " + hour + ":" +
			// ((min<10)?("0" + min):min);
			rs = dateStr;
		} else if (((j - i) / dayTime) > 0) {
			rs = ((j - i) / dayTime) + "天前";
		} else if (((j - i) / hourTime) > 0) {
			rs = ((j - i) / hourTime) + "小时前";
		} else if (((j - i) / minTime) > 0) {
			rs = ((j - i) / minTime) + "分钟前";
		} else if (((j - i) / secTime) > 0) {
			rs = ((j - i) / secTime) + "秒前";
		} else {
			rs = "刚刚";
		}
		return rs;
	}

	public static String getDuration(int time) {
		String result = "";
		if (time / 60 > 0) {
			result = time / 60 + "'" + time % 60 + "\"";
		} else {
			result = time + "\"";
		}
		return result;
	}

	public static String getHowLongStr(Calendar date) {
		String rs = "";
		Long i = date.getTimeInMillis();
		Date now = new Date();
		Long j = now.getTime();
		long dayTime = 1000 * 60 * 60 * 24;
		long hourTime = 1000 * 60 * 60;
		long minTime = 1000 * 60;
		long secTime = 1000;
		if (((j - i) / dayTime) > 2) {
			int month = date.get(Calendar.MONTH);
			int day = date.get(Calendar.DAY_OF_MONTH);
			int hour = date.get(Calendar.HOUR_OF_DAY);
			int min = date.get(Calendar.MINUTE);
			rs = (month + 1) + "月" + (day) + "日"
			// + " " + hour + ":" + ((min<10)?("0" + min):min)
			;
		} else if (((j - i) / dayTime) > 0) {
			rs = ((j - i) / dayTime) + "天前";
		} else if (((j - i) / hourTime) > 0) {
			rs = ((j - i) / hourTime) + "小时前";
		} else if (((j - i) / minTime) > 0) {
			rs = ((j - i) / minTime) + "分钟前";
		} else if (((j - i) / secTime) > 0) {
			rs = ((j - i) / secTime) + "秒前";
		} else {
			rs = "刚刚";
		}
		return rs;
	}

	/** 解析数据 */
	public static String getNum(String strNum) {
		if (strNum == null || strNum.equals("") || strNum.equals("null")) {
			return "0";
		}
		long num = Long.parseLong(strNum);
		if (num <= 9999) {// 1万以内
			return strNum;
		} else if (num > 9999 && num <= 99999) {// 10万以内
			// 10000 10999 19999
			long first = num / 10000;
			long sec = num / 1000 % 10;
			return "" + first + "." + sec + "万";
		} else if (num > 99999 && num <= 999999) {// 100万以内
			// 100000 109999 199999
			long first = num / 10000;
			long sec = num / 1000 % 10;
			return "" + first + "." + sec + "万";
		} else if (num > 999999 && num <= 99999999) {// 1000万以内
			// 10000 10999 19999
			long first = num / 10000;
			long sec = num / 1000 % 10;
			return "" + first + "." + sec + "万";
		} else {
			return "999万+";
		}
	}

	// public static SpannableString getJustHighLightLinks(String txt) {
	// //hack to fix android imagespan bug,see
	// http://stackoverflow.com/questions/3253148/imagespan-is-cut-off-incorrectly-aligned
	// //if string only contains emotion tags,add a empty char to the end
	// String hackTxt;
	// if (txt.startsWith("[") && txt.endsWith("]")) {
	// hackTxt = txt + " ";
	// } else {
	// hackTxt = txt;
	// }
	// SpannableString value;
	// TransformFilter mentionFilter = new TransformFilter() {
	// public final String transformUrl(final Matcher match, String url) {
	// return match.group(1);
	// }
	// };
	//
	// // Match @mentions and capture just the username portion of the text.
	// Pattern pattern = Pattern.compile("@([a-zA-Z0-9_\\-\\u4e00-\\u9fa5]+)");
	// String scheme = "org.qii.weiciyuan://";
	// value = MyLinkify.getJustHighLightLinks(hackTxt, pattern, scheme, null,
	// mentionFilter);
	//
	// value = MyLinkify.addJUstHighLightLinks(value, MyLinkify.WEB_URLS);
	//
	//
	// Pattern dd = Pattern.compile("#([a-zA-Z0-9_\\-\\u4e00-\\u9fa5]+)#");
	// value = MyLinkify.getJustHighLightLinks(value, dd, scheme, null,
	// mentionFilter);
	//
	// // ListViewTool.addEmotions(value);
	//
	// return value;
	// }

	/**
	 * TransformFilter enables client code to have more control over how matched
	 * patterns are represented as URLs.
	 * <p/>
	 * For example: when converting a phone number such as (919) 555-1212 into a
	 * tel: URL the parentheses, white space, and hyphen need to be removed to
	 * produce tel:9195551212.
	 */
	public interface TransformFilter {
		/**
		 * Examines the matched text and either passes it through or uses the
		 * data in the Matcher state to produce a replacement.
		 * 
		 * @param match
		 *            The regex matcher state that found this URL text
		 * @param url
		 *            The text that was matched
		 * @return The transformed form of the URL
		 */
		String transformUrl(final Matcher match, String url);
	}

	// /**
	// * MatchFilter enables client code to have more control over
	// * what is allowed to match and become a link, and what is not.
	// * <p/>
	// * For example: when matching web urls you would like things like
	// * http://www.example.com to match, as well as just example.com itelf.
	// * However, you would not want to match against the domain in
	// * support@example.com. So, when matching against a web url pattern you
	// * might also include a MatchFilter that disallows the match if it is
	// * immediately preceded by an at-sign (@).
	// */
	// public interface MatchFilter {
	// /**
	// * Examines the character span matched by the pattern and determines
	// * if the match should be turned into an actionable link.
	// *
	// * @param s The body of text against which the pattern
	// * was matched
	// * @param start The index of the first character in s that was
	// * matched by the pattern - inclusive
	// * @param end The index of the last character in s that was
	// * matched - exclusive
	// * @return Whether this match should be turned into a link
	// */
	// boolean acceptMatch(CharSequence s, int start, int end);
	// }
	//
	// public static final SpannableString getJustHighLightLinks(CharSequence s,
	// Pattern p, String scheme,
	// MatchFilter matchFilter, TransformFilter transformFilter) {
	// SpannableString value = SpannableString.valueOf(s);
	//
	// if (addLinks(value, p, scheme, matchFilter, transformFilter)) {
	// return value;
	// }
	//
	// return new SpannableString(s);
	// }

	public static byte[] bmpToByteArray(final Bitmap bmp,
			final boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bmp.compress(CompressFormat.PNG, 100, output);
		if (needRecycle) {
			bmp.recycle();
		}

		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	public static byte[] getHtmlByteArray(final String url) {
		URL htmlUrl = null;
		InputStream inStream = null;
		try {
			htmlUrl = new URL(url);
			URLConnection connection = htmlUrl.openConnection();
			HttpURLConnection httpConnection = (HttpURLConnection) connection;
			int responseCode = httpConnection.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				inStream = httpConnection.getInputStream();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] data = inputStreamToByte(inStream);

		return data;
	}

	public static byte[] inputStreamToByte(InputStream is) {
		try {
			ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
			int ch;
			while ((ch = is.read()) != -1) {
				bytestream.write(ch);
			}
			byte imgdata[] = bytestream.toByteArray();
			bytestream.close();
			return imgdata;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public static byte[] readFromFile(String fileName, int offset, int len) {
		if (fileName == null) {
			return null;
		}

		File file = new File(fileName);
		if (!file.exists()) {
			// Log.i(TAG, "readFromFile: file not found");
			return null;
		}

		if (len == -1) {
			len = (int) file.length();
		}

		// Log.d(TAG, "readFromFile : offset = " + offset + " len = " + len +
		// " offset + len = " + (offset + len));

		if (offset < 0) {
			// Log.e(TAG, "readFromFile invalid offset:" + offset);
			return null;
		}
		if (len <= 0) {
			// Log.e(TAG, "readFromFile invalid len:" + len);
			return null;
		}
		if (offset + len > (int) file.length()) {
			// Log.e(TAG, "readFromFile invalid file len:" + file.length());
			return null;
		}

		byte[] b = null;
		try {
			RandomAccessFile in = new RandomAccessFile(fileName, "r");
			b = new byte[len]; // 创建合适文件大小的数组
			in.seek(offset);
			in.readFully(b);
			in.close();

		} catch (Exception e) {
			// Log.e(TAG, "readFromFile : errMsg = " + e.getMessage());
			e.printStackTrace();
		}
		return b;
	}

	private static final int MAX_DECODE_PICTURE_SIZE = 1920 * 1440;

	public static Bitmap extractThumbNail(final String path, final int height,
			final int width, final boolean crop) {
		Assert.assertTrue(path != null && !path.equals("") && height > 0
				&& width > 0);

		BitmapFactory.Options options = new BitmapFactory.Options();

		try {
			options.inJustDecodeBounds = true;
			Bitmap tmp = BitmapFactory.decodeFile(path, options);
			if (tmp != null) {
				tmp.recycle();
				tmp = null;
			}

			// Log.d(TAG, "extractThumbNail: round=" + width + "x" + height +
			// ", crop=" + crop);
			final double beY = options.outHeight * 1.0 / height;
			final double beX = options.outWidth * 1.0 / width;
			// Log.d(TAG, "extractThumbNail: extract beX = " + beX + ", beY = "
			// + beY);
			options.inSampleSize = (int) (crop ? (beY > beX ? beX : beY)
					: (beY < beX ? beX : beY));
			if (options.inSampleSize <= 2) {
				options.inSampleSize = 2;
			}

			// NOTE: out of memory error
			while (options.outHeight * options.outWidth / options.inSampleSize > MAX_DECODE_PICTURE_SIZE) {
				options.inSampleSize++;
			}

			int newHeight = height;
			int newWidth = width;
			if (crop) {
				if (beY > beX) {
					newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
				} else {
					newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
				}
			} else {
				if (beY < beX) {
					newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
				} else {
					newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
				}
			}

			options.inJustDecodeBounds = false;

			// Log.i(TAG, "bitmap required size=" + newWidth + "x" + newHeight +
			// ", orig=" + options.outWidth + "x" + options.outHeight +
			// ", sample=" + options.inSampleSize);
			Bitmap bm = BitmapFactory.decodeFile(path, options);
			if (bm == null) {
				// Log.e(TAG, "bitmap decode failed");
				return null;
			}

			// Log.i(TAG, "bitmap decoded size=" + bm.getWidth() + "x" +
			// bm.getHeight());
			final Bitmap scale = Bitmap.createScaledBitmap(bm, newWidth,
					newHeight, true);
			if (scale != null) {
				bm.recycle();
				bm = scale;
			}

			if (crop) {
				final Bitmap cropped = Bitmap.createBitmap(bm,
						(bm.getWidth() - width) >> 1,
						(bm.getHeight() - height) >> 1, width, height);
				if (cropped == null) {
					return bm;
				}

				bm.recycle();
				bm = cropped;
				// Log.i(TAG, "bitmap croped size=" + bm.getWidth() + "x" +
				// bm.getHeight());
			}
			return bm;

		} catch (final OutOfMemoryError e) {
			// Log.e(TAG, "decode bitmap failed: " + e.getMessage());
			options = null;
		}

		return null;
	}

	public static boolean isTopActivity(Context context, String activityName) {
		String packageName = "com.v1.video.activity.";
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
		String strName = cn.getClassName();
		if (strName != null && strName.equals(packageName + activityName)) {
			return true;
		}
		return false;

	}

	public static MyDialog createDialog(Context context, int style) {

		MyDialog dialog = new MyDialog(context, style);
		dialog.setContentView(R.layout.dialog_promt_cancel_action);
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		return dialog;

	}

	public static MyDialog createMyDialog(Context context, int style,
			int layoutId) {

		MyDialog dialog = new MyDialog(context, style);
		dialog.setContentView(layoutId);
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);

		return dialog;
	}

	// //生成圆角图片
	// public static Bitmap GetRoundedCornerBitmap(Bitmap bitmap) {
	// try {
	// Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
	// bitmap.getHeight(), Config.ARGB_8888);
	// Canvas canvas = new Canvas(output);
	// final Paint paint = new Paint();
	// final Rect rect = new Rect(0, 0, bitmap.getWidth(),
	// bitmap.getHeight());
	// final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(),
	// bitmap.getHeight()));
	// final float roundPx = 14;//设置这 可以改变取舍多少幅度
	// paint.setAntiAlias(true);
	// canvas.drawARGB(0, 0, 0, 0);
	// paint.setColor(Color.BLACK);
	// canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
	// paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
	//
	// final Rect src = new Rect(0, 0, bitmap.getWidth(),
	// bitmap.getHeight());
	//
	// canvas.drawBitmap(bitmap, src, rect, paint);
	// return output;
	// } catch (Exception e) {
	// return bitmap;
	// }
	// }

	/**
	 * 获取一个0到flag之间的随机数
	 * 
	 * @param flag
	 * @return
	 */
	public static int getRandom(int flag) {

		return new Random().nextInt(flag);

	}

	// 它是用来标识在 Span 范围内的文本前后输入新的字符时是否把它们也应用这个效果。
	// 分别有 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(前后都不包括)、
	// Spanned.SPAN_INCLUSIVE_EXCLUSIVE(前面包括，后面不包括)、
	// Spanned.SPAN_EXCLUSIVE_INCLUSIVE(前面不包括，后面包括)、
	// Spanned.SPAN_INCLUSIVE_INCLUSIVE(前后都包括)。
	/**
	 * 给目标文本对象的局部文字设置颜色
	 * 
	 * @param target
	 *            目标文本对象
	 * @param color
	 *            目标文本颜色
	 * @param partWords
	 *            目标文本
	 */
	public static void ChangeTextViewPartWordsTextColor(TextView target,
			int color, String partWords) {
		if (target == null || partWords == null || partWords.length() == 0)
			return;
		String value = target.getText().toString().trim();
		int start = value.indexOf(partWords);
		if (start < 0)
			return;
		SpannableStringBuilder builder = new SpannableStringBuilder(
				target.getText());
		ForegroundColorSpan redSpan = new ForegroundColorSpan(color);
		builder.setSpan(redSpan, start, start + partWords.length(),
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		target.setText(builder);
	}

	/**
	 * 给目标文本对象设置富媒体字体
	 * 
	 * @param target
	 *            目标文本对象
	 * @param valueStr
	 *            待设置的文字
	 * @param color
	 *            目标字体颜色
	 * @param partWords
	 *            目标字体
	 */
	public static void ChangeTextViewPartWordsTextColor(TextView target,
			String valueStr, int color, String partWords) {
		if (target == null || valueStr == null || valueStr.length() == 0
				|| partWords == null || partWords.length() == 0)
			return;
		int start = valueStr.indexOf(partWords);
		if (start < 0)
			return;
		SpannableStringBuilder builder = new SpannableStringBuilder(valueStr);
		ForegroundColorSpan redSpan = new ForegroundColorSpan(color);
		builder.setSpan(redSpan, start, start + partWords.length(),
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		target.setText(builder);
	}
	
	/**
	 * 给目标文本对象设置富媒体字体
	 * 
	 * @param target
	 *            目标文本对象
	 * @param valueStr
	 *            待设置的文字
	 * @param partWords
	 *            目标字体
	 */
	public static void ChangeTextViewPartWordsBold(TextView target,
			String valueStr, String partWords) {
		if (target == null || valueStr == null || valueStr.length() == 0
				|| partWords == null || partWords.length() == 0)
			return;
		int start = valueStr.indexOf(partWords);
		if (start < 0)
			return;
		SpannableStringBuilder builder = new SpannableStringBuilder(valueStr); 
		builder.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, start + partWords.length(),
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		target.setText(builder);
	}

	/**
	 * 读取文本文件
	 * @param context
	 * @param strFilePath
	 * @return
	 */
	public static String ReadTxtFile(Context context,String strFilePath) {
		if(context == null){
			return "";
		}
		String cachePath = context.getCacheDir().getAbsolutePath();
		String path = cachePath + File.separator + strFilePath;
		String content="";
		StringBuffer sb = new StringBuffer("");
		// 打开文件
		File file = new File(path);
		// 如果path是传递过来的参数，可以做一个非目录的判断
		if (file.isDirectory()) {
			Logger.d("TestFile", "The File doesn't not exist.");
		} else {
			if(!file.exists())
				return "";
			try {
				InputStream instream = new FileInputStream(file);
				if (instream != null) {
					InputStreamReader inputreader = new InputStreamReader(
							instream);
					BufferedReader buffreader = new BufferedReader(inputreader);
					String line;
					// 分行读取
					while ((line = buffreader.readLine()) != null) {
						sb.append(line);
						sb.append("\n");
					}
					content=sb.toString();
					instream.close();
				}
			} catch (java.io.FileNotFoundException e) {
				Logger.d("TestFile", "The File doesn't not exist.");
			} catch (IOException e) {
				Logger.d("TestFile", e.getMessage());
			}
		}
		return content;
	}

	/**
	 * 缓冲json文件
	 * 
	 * @param filename
	 *            文件名称
	 * @param json
	 *            json数据
	 */
	public static void CacheData(Context context, String filename, String json) {
		if(context == null){
			return;
		}
		String cachePath = context.getCacheDir().getAbsolutePath();
		String fullFilePath = cachePath + File.separator + filename;
		File file = new File(fullFilePath);

		try {
			FileOutputStream outs = new FileOutputStream(file, false);
			byte[] bytes = json.getBytes();  
			outs.write(bytes);
			outs.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e){
			e.printStackTrace();
		}
	}

	/**
	 * 过滤表情图
	 */
	public static InputFilter[] GetEmojiFilter(){
		InputFilter[] emojiFilter = new InputFilter[]{
				new InputFilter() {
					Pattern emoji = Pattern.compile ("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE );
					@Override
					public CharSequence filter(CharSequence source, int start, int end,
							Spanned dest, int dstart, int dend) {
						Matcher emojiMatcher = emoji.matcher ( source );
						if(emojiMatcher.find()){
							return " ";
						}else{
							return null;
						}
					}
				}
			};
		
		return emojiFilter;
	}
	
	/**
	 * 过滤表情字符
	 * @param contentEd
	 */
	public static void AddTextWatcher(final EditText contentEd){
		
	}
	
	/**
	 * 过滤表情字符
	 * @param contentEd
	 *//*
	public static void AddTextWatcher2(final EditText contentEd){
		
		TextWatcher watcher = new TextWatcher() {
			// 匹配非表情符号的正则表达式
			String reg = "^([a-z]|[A-Z]|#|[0-9]|[\u2E80-\u9FFF]){3,}|@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?|[wap.]{4}|[www.]{4}|[blog.]{5}|[bbs.]{4}|[.com]{4}|[.cn]{3}|[.net]{4}|[.org]{4}|[http://]{7}|[ftp://]{6}$";

			Pattern pattern = Pattern.compile(reg);
			// 输入表情前的光标位置
			int cursorPos;
			// 输入表情前EditText中的文本
			String tmp;
			// 是否重置了EditText的内容
			boolean resetText;
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (!resetText) {
					if (count >= 3) {// 表情符号的字符长度最小为3
						// 提取输入的长度大于3的文本
						CharSequence input = s.subSequence(cursorPos, cursorPos
								+ count);
						// 正则匹配是否是表情符号
						Matcher matcher = pattern.matcher(input.toString());
						if (!matcher.matches()) {
							resetText = true;
							// 是表情符号就将文本还原为输入表情符号之前的内容
							contentEd.setText(tmp+" ");
							contentEd.invalidate();
							contentEd.setSelection(contentEd.length());
						}
					}
				} else {
					resetText = false;
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				if (!resetText) {
					cursorPos = contentEd.getSelectionEnd();
					tmp = s.toString();// 这里用s.toString()而不直接用s是因为如果用s，那么，tmp和s在内存中指向的是同一个地址，s改变了，tmp也就改变了，那么表情过滤就失败了
				}

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		};
		
		contentEd.addTextChangedListener(watcher);
	}*/
}
